//
//  Server.m
//  XXX
//
//  Created by Xiaoshiheng_pro on 2017/2/18.
//  Copyright © 2017年 Xiaoshiheng_pro. All rights reserved.
//

#import "Server.h"

@interface Server()<GCDAsyncSocketDelegate>

@end

@implementation Server

+ (instancetype)ServerInit{
    static Server* ServerMode;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        ServerMode = [[Server alloc] init];
        [ServerMode initSet];
    });
    return ServerMode;
}

- (void)initSet{
    
    // 1、初始化服务器socket，在主线程力回调
    self.serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    [self startAcceptOnPort];
    
    
    
}

- (void)startAcceptOnPort{
    
    //2、开放哪一个端口
    NSError *error = nil;
    BOOL result = [self.serverSocket acceptOnPort:[@"8080" integerValue] error:&error];
    if (result && error == nil) {
        //开放成功
        NSLog(@"开放成功");

    }
    
}
///发送消息成功
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    if(self.delegate && [self.delegate respondsToSelector:@selector(serverSocket:didWriteDataWithTag:)]){
        
        [self.delegate serverSocket:sock didWriteDataWithTag:tag];
    }
}
//收到消息  ok
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
    //    NSLog(@"%s", __PRETTY_FUNCTION__);
    if (HEADER_TAG == tag)
    {
        NSUInteger length = 0;
        [data getBytes:&length length:sizeof(NSUInteger)];
        
        NSMutableData *buffer = [NSMutableData data];
        [self.clinetSocket readDataToLength:length withTimeout:-1 buffer:buffer bufferOffset:0 tag:BODY_TAG];
    }
    else if (BODY_TAG == tag)
    {
        
        NSUInteger length = sizeof(NSUInteger);
        NSMutableData *buffer = [NSMutableData data];
        [self.clinetSocket readDataToLength:length withTimeout:-1 buffer:buffer bufferOffset:0 tag:HEADER_TAG];
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(serverSocket:didReadData:withTag:)]){
            
            [self.delegate serverSocket:sock didReadData:data withTag:tag];
        }
    }

}
#pragma mark - 服务器socket Delegate  ok
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket{
    

    
    /* 开始从 socket 中读取字节流 */
    // P.S. 每次收到回调后立即读取数据会断开连接，所以采用延迟一秒后再读数据
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        
        
        
        //保存客户端的socket
        self.clinetSocket = newSocket;
        
        NSUInteger length = sizeof(NSUInteger);
        NSMutableData *buffer = [NSMutableData data];
        [self.clinetSocket readDataToLength:length withTimeout:-1 buffer:buffer bufferOffset:0 tag:HEADER_TAG];
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(serverSocket:didAcceptNewSocket:)]){
            
            [self.delegate serverSocket:sock didAcceptNewSocket:newSocket];
        }
        

    });
    
}
///读取接收长度
- (void)socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag{
    
    NSLog(@"%lu", partialLength);
    
}
///发送进度
- (void)socket:(GCDAsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag{
    
}
///失去连接 ok
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    
    
//    NSLog(@"失去连接");
    if(self.delegate && [self.delegate respondsToSelector:@selector(serverSocketDidDisconnect:withError:)]){
        
        [self.delegate serverSocketDidDisconnect:sock withError:err];
    }
}



@end
